<?php

/**
 * 导入模型&词条
 * 按照约定格式存放
 */

namespace App\Console\Commands;

use App\Datas\ModelList;
use App\Datas\ModelStyle;
use Illuminate\Console\Command;

use App\Tools\File;
use Illuminate\Support\Facades\DB;

class ImportModelStyleCommand extends BaseCommand {
	/**
	 * 命令行执行命令
	 * @var string
	 */
	protected $signature = 'importModelStyle';

	/**
	 * 命令描述
	 *
	 * @var string
	 */
	protected $description = 'import model style list';

	public function handle() {
		//$this->import();
		//$this->replenish();
		$this->ceshi();

		exit;
	}

	/**
	 * 补充
	 */
	private function replenish() {
		$this->import();
	}

	private function ceshi(){

		$list = DB::table('system_device')->whereNull('install_time')->select('id','created_at','appsfly_id','platform','af_channel')->limit(30000)->get()->toArray();

		foreach ($list as $key => $value) {
            $afInfo = DB::table('af_log')->where('appsflyer_id',$value->appsfly_id)->first();
            $updateArr = [];
            if ($afInfo) {
                $content = json_decode($afInfo->content, true);
                $time = $content['install_time_selected_timezone'] ?? $content['install_time'];
                if ($time) {
                    $time = date('Y-m-d H:i:s',strtotime($time));
                }else{
                	$time = $value->created_at;
                }
                $media_source = $content['media_source'];
                if ($value->platform == 'android') { //安卓的
                    if ($content['media_source'] == 'organic') {
                        $media_source = 'googleadwords_int';
                    }
                    if ($content['media_source'] == 'restricted') {
                        $media_source = 'Facebook Ads';
                    }
                    if (empty($value->af_channel)) {
                     	$updateArr['af_channel'] = $media_source;
                	}      
                }
                        
            }else{
            	$time = $value->created_at;
            }
            $updateArr['install_time'] = $time;
            DB::table('system_device')->where('id',$value->id)->update($updateArr);
            echo $value->id.PHP_EOL;
        }

        echo 'ok';

	}

	/**
	 * 导入
	 */
	private function import() {
		$aImportAmount = [];
		$sImportFolder = $this->rootPath.'/storage/tmp/';
		$sCsvFile = 'prompt.csv';
		$aImportModelList = $this->_getImportModelList($sImportFolder);
		foreach($aImportModelList as $sImportModel) {
			echo $sImportModel.PHP_EOL;
			//$aImportModel = explode('-', $sImportModel);
			//if(2 != count($aImportModel)) {
			//	continue;
			//}
			//$sModelID = $aImportModel[1];

			$sModelID = $sImportModel;
			$sCsvFilePath = $sImportFolder.$sImportModel.'/'.$sCsvFile;
			if(!file_exists($sCsvFilePath)) {
				continue;
			}

			$aCSVList = $this->_getCSVFile($sCsvFilePath);
			if(empty($aCSVList)) {
				echo 'CSV 文件空'.PHP_EOL;
				continue;
			}
			echo 'Start'.PHP_EOL;
			foreach($aCSVList as $aCSV) {
				if(empty($aCSV)) {
					continue;
				}
				$sFile = ltrim(trim($aCSV[0]), '/');
				$sFile = pathinfo($sFile, PATHINFO_FILENAME);
				$sFile .= '.webp';

				$sPrompt = trim($aCSV[1]);
				$sNegativePrompt = trim($aCSV[2]);

				$iPromptLen = strlen($sPrompt);
				if($iPromptLen > 2000) {
					continue;
				}

				$sImgPath = $sImportFolder.$sImportModel.'/'.$sFile;
				if(!file_exists($sImgPath)) {
					continue;
				}

				$_sImg = '/style_s/'.$sModelID.'/'.$sFile;
				$_aWhere = ['model_id' => $sModelID, 'img' => $_sImg];
				$Style = ModelStyle::getInstance()->getOneInfo($_aWhere);
				if(!empty($Style)) {
					continue;
				}

				//$sCreateAt = date('Y-m-d H:i:s', strtotime($aCSV[6]));
				$sCreateAt = date('Y-m-d H:i:s');
				$aStyle = [
					'model_id' => $sModelID, 'name' => null,

					'img' => $_sImg,

					'prompt' => $sPrompt, 'negative_prompt' => $sNegativePrompt,

					'sort' => 10, 'use_num' => 0, 'dot' => 20, 'status' => 0, 'create_at' => $sCreateAt,
					'update_at' => $sCreateAt
				];
				ModelStyle::getInstance()->insert($aStyle);

				if(isset($aImportAmount[$sModelID])) {
					$aImportAmount[$sModelID] += 1;
				} else {
					$aImportAmount[$sModelID] = 1;
				}
			}
			echo 'End'.PHP_EOL;
		}
		var_dump($aImportAmount);
	}

	/**
	 * 读取CSV文件
	 * @param string $sFile
	 * @return array|false
	 */
	private function _getCSVFile($sFile) {
		if(!file_exists($sFile)) {
			return false;
		}
		$oFOpen = fopen($sFile, 'rb');
		$aDataList = [];
		while(!feof($oFOpen)) {
			$aDataList[] = fgetcsv($oFOpen);
		}
		fclose($oFOpen);
		return $aDataList;
	}

	/**
	 * 获取文件名
	 * @param string $sFolder
	 * @param string $sFile
	 * @param string $sExt
	 * @return string|boolean
	 */
	private function _getImgAllFileName($sFolder, $sFile, $sExt = 'webp') {
		if(empty($sFile)) {
			return false;
		}
		$aList = glob($sFolder.DIRECTORY_SEPARATOR.$sFile.'-*.'.$sExt, 1);
		if(empty($aList)) {
			return false;
		}

		$sFile = (isset($aList[0]) && !empty($aList[0])) ? pathinfo($aList[0], PATHINFO_BASENAME) : null;
		return $sFile;
	}

	/**
	 * 获取目录列表
	 * @param string $sFolder
	 * @param string $sPattern
	 * @return array|false
	 */
	private function _getImportModelList($sFolder, $sPattern = '*') {
		if(empty($sFolder)) {
			return false;
		}

		$sFolder = rtrim($sFolder, '/');

		$aList = glob($sFolder.DIRECTORY_SEPARATOR.$sPattern, GLOB_ONLYDIR);
		if(empty($aList)) {
			return false;
		}

		$aFolder = [];
		foreach($aList as $_sFolder) {
			$_sFolder = str_replace($sFolder, '', $_sFolder);
			$_sFolder = ltrim($_sFolder, '/');
			if('ok' == $_sFolder) {
				continue;
			}
			$aFolder[] = $_sFolder;
		}
		return $aFolder;
	}


	private function getStyleByWhere($aWhere) {
		$Data = DB::table('model_style_special')->where($aWhere)->first()->toArray();
		return $Data;
	}

	private function updateStyleByWhere($aWhere, $aUpdate) {
		return DB::table('model_style_special')->where($aWhere)->update($aUpdate);
	}

	private function addStyle($aStyle) {
		ModelStyle::getInstance()->insert($aStyle);
	}
}